"use client";

import { useState, useRef, useEffect } from "react";

interface AudioUploaderProps {
  onUpload: (file: File) => void;
  isLoading: boolean;
  onReset: () => void;
}

/**
 * 音频文件上传组件
 * 功能：处理音频文件的选择、验证、预览和上传
 * 参数：上传回调、加载状态、重置回调
 * 使用场景：用户上传音频文件进行情感识别
 */
export default function AudioUploader({ onUpload, isLoading, onReset }: AudioUploaderProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [audioUrl, setAudioUrl] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const audioRef = useRef<HTMLAudioElement>(null);

  // 支持的音频格式
  const supportedFormats = [".wav", ".mp3", ".flac", ".m4a"];
  const maxFileSize = 10 * 1024 * 1024; // 10MB

  /**
   * 验证文件是否符合要求
   * 参数：file - 待验证的文件
   * 返回值：验证结果和错误信息
   */
  const validateFile = (file: File): { isValid: boolean; error?: string } => {
    // 检查文件大小
    if (file.size > maxFileSize) {
      return {
        isValid: false,
        error: `文件大小不能超过 ${Math.round(maxFileSize / (1024 * 1024))}MB`
      };
    }

    // 检查文件类型
    const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
    if (!supportedFormats.includes(fileExtension)) {
      return {
        isValid: false,
        error: `不支持的文件格式，请使用: ${supportedFormats.join(', ')}`
      };
    }

    return { isValid: true };
  };

  /**
   * 处理文件选择
   */
  const handleFileSelect = (file: File) => {
    const validation = validateFile(file);
    
    if (!validation.isValid) {
      alert(validation.error);
      return;
    }

    setSelectedFile(file);
    
    // 创建音频预览URL
    if (audioUrl) {
      URL.revokeObjectURL(audioUrl); // 清理之前的URL
    }
    const newAudioUrl = URL.createObjectURL(file);
    setAudioUrl(newAudioUrl);
  };

  /**
   * 处理文件上传
   */
  const handleUpload = () => {
    if (selectedFile) {
      onUpload(selectedFile);
    }
  };

  /**
   * 重置组件状态
   */
  const handleReset = () => {
    setSelectedFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
    // 清理音频URL
    if (audioUrl) {
      URL.revokeObjectURL(audioUrl);
      setAudioUrl(null);
    }
    onReset();
  };

  // 组件卸载时清理资源
  useEffect(() => {
    return () => {
      if (audioUrl) {
        URL.revokeObjectURL(audioUrl);
      }
    };
  }, [audioUrl]);

  /**
   * 处理拖拽上传
   */
  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileSelect(e.dataTransfer.files[0]);
    }
  };

  /**
   * 处理文件输入变化
   */
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileSelect(e.target.files[0]);
    }
  };

  return (
    <div className="space-y-4">
      {/* 拖拽上传区域 */}
      <div
        className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
          dragActive
            ? "border-blue-500 bg-blue-50 dark:bg-blue-900/20"
            : "border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500"
        }`}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
      >
        <div className="space-y-4">
          <div className="text-4xl">🎵</div>
          <div>
            <p className="text-lg font-medium text-gray-900 dark:text-white">
              拖拽音频文件到此处
            </p>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              或点击下方按钮选择文件
            </p>
          </div>
          
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={isLoading}
          >
            选择音频文件
          </button>
          
                     <input
             ref={fileInputRef}
             type="file"
             accept={supportedFormats.join(",")}
             onChange={handleFileChange}
             className="hidden"
             aria-label="选择音频文件"
           />
        </div>
      </div>

      {/* 文件信息显示和音频预览 */}
      {selectedFile && (
        <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="text-2xl">🎶</div>
              <div>
                <p className="font-medium text-gray-900 dark:text-white">
                  {selectedFile.name}
                </p>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {(selectedFile.size / (1024 * 1024)).toFixed(2)} MB
                </p>
              </div>
            </div>
            <button
              onClick={handleReset}
              className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              title="移除文件"
            >
              ✕
            </button>
          </div>
          
          {/* 音频预览播放器 */}
          {audioUrl && (
            <div className="border-t border-gray-200 dark:border-gray-600 pt-4">
              <div className="flex items-center space-x-3">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  🎧 音频预览:
                </span>
                <audio
                  ref={audioRef}
                  src={audioUrl}
                  controls
                  className="flex-1 h-8"
                  preload="metadata"
                >
                  您的浏览器不支持音频播放
                </audio>
              </div>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                💡 您可以先预览音频内容，确认无误后再进行情感识别
              </p>
            </div>
          )}
        </div>
      )}

      {/* 操作按钮 */}
      <div className="flex space-x-3">
        <button
          onClick={handleUpload}
          disabled={!selectedFile || isLoading}
          className="flex-1 inline-flex justify-center items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isLoading ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
              分析中...
            </>
          ) : (
            "开始情感识别"
          )}
        </button>
        
        <button
          onClick={handleReset}
          disabled={!selectedFile || isLoading}
          className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-sm font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          重置
        </button>
      </div>

      {/* 格式说明 */}
      <div className="text-xs text-gray-500 dark:text-gray-400 mt-2">
        <p>支持格式: {supportedFormats.join(", ")}</p>
        <p>最大文件大小: {Math.round(maxFileSize / (1024 * 1024))}MB</p>
      </div>
    </div>
  );
} 